<template>
  <div class="home-content">
    <div class="side-menu" v-if="false">
      <div class="head">
        <img src="../../assets/images/head-logo.svg" alt="" />
        <h1>收藏库</h1>
      </div>
      <ul class="menu-body">
        <li
          v-for="(item, index) in sideMenuList"
          :key="index"
          @click="handleSelectAction(item.type)"
          :class="item.type == selectType ? 'active' : ''"
        >
          <el-icon><component :is="item.icon"></component></el-icon>
          <span>{{ item.label }}</span>
        </li>
      </ul>
      <div class="tree-side">
        <h4>我的收藏夹</h4>
        <el-tree
          ref="tableTreeSide"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          :expand-on-click-node="false"
          accordion
          :default-expanded-keys="defaultExpandNodes"
          :show-checkbox="false"
        >
          <template #default="{ node }">
            <div class="add-tree-node" v-if="node.data.type == 'input'">
              <el-input
                ref="treeInputRef"
                v-model="node.data.label"
                @blur="addNewNode(node)"
                @keyup.enter="treeInputRef.blur()"
              ></el-input>
            </div>
            <div
              class="custom-tree-node"
              v-else
              @mouseenter="node.data.showIcon = true"
              @mouseleave="node.data.showIcon = false"
            >
              <span class="node-label" @click="handleClickNode(node)">{{
                node.label
              }}</span>
              <span class="node-icon" v-show="node.data.showIcon">
                <el-icon v-if="node.data.id == 0" @click="handleAddNode(node)"
                  ><Plus
                /></el-icon>
                <el-icon
                  style="margin-left: 10px"
                  v-if="node.data.id != 0"
                  @click="deleteNode(node)"
                  ><Delete
                /></el-icon>
              </span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <book-marks-list ref="bookmarksRef" v-model="query"></book-marks-list>
  </div>
</template>

<script setup>
import { Comment, Pointer, Star, Timer } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, markRaw, nextTick } from "vue";
import { mAxios, encodeURL } from "~/utils/axios/axios.js";
import moment from "moment";
const userId = Number(sessionStorage.getItem("user_id"));
// 获取当前日期
const currentDate = moment();
// 获取一周前的日期
const oneWeekAgo = moment().subtract(7, "days");
const bookmarksRef = ref();
const query = ref({
  userId: null,
  // begin: oneWeekAgo.format("YYYY-MM-DD HH:mm:ss"),
  // end: currentDate.format("YYYY-MM-DD HH:mm:ss"),
});

const sideMenuList = [
  { label: "最新", icon: markRaw(Timer), type: "new" },
  { label: "星标", icon: markRaw(Star), type: "asterisk" },
  // { label: '我的评论', icon: markRaw(Comment), type: 'comment' },
  // { label: '我的喜欢', icon: markRaw(Pointer), type: 'likes' }
];
const selectType = ref("new");
const handleSelectAction = (type) => {
  selectType.value = type;
  switch (type) {
    case "new":
      query.value = {
        userId,
        begin: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
        end: moment().format("YYYY-MM-DD HH:mm:ss"),
      };
      break;
    case "asterisk":
      query.value = {
        userId,
        asterisk: 1,
      };
      break;
  }
};
// 树形组件相关
const tableTreeSide = ref();
const treeData = ref([{ id: 0, groupName: "全部", child: [] }]);
const treeProps = {
  children: "child",
  label: "groupName",
  value: "id",
};
const defaultExpandNodes = [0];
const getTreeSideData = () => {
  mAxios.get(`group/list/${userId}`).then((res) => {
    treeData.value[0].child = res.data.data;
  });
};
const treeInputRef = ref();
const handleAddNode = (node) => {
  node.expand();
  setTimeout(() => {
    node.data.child.unshift({
      label: "",
      child: [],
      type: "input",
    });
    nextTick(() => {
      treeInputRef.value.focus();
    });
  }, 300);
};
const addNewNode = (node) => {
  let params = {
    userId,
    groupName: node.data.label,
  };
  if (params.groupName != "") {
    mAxios.post(`group`, params).then((res) => {
      res.data.succeed
        ? ElMessage.success("添加成功")
        : ElMessage.error("添加失败");
      getTreeSideData();
    });
  } else {
    tableTreeSide.value.remove(node);
  }
};
const deleteNode = (node) => {
  ElMessageBox.confirm(
    "此操作会删除分组下所有的书签，确定要删除分组" + node.data.groupName + "？",
    "删除分组",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      center: true,
      closeOnClickModal: false,
      type: "warning",
    }
  ).then(() => {
    mAxios.delete("group", { data: { id: node.data.id } }).then((res) => {
      res.data.succeed
        ? ElMessage.success("删除成功")
        : ElMessage.error("删除失败");
      getTreeSideData();
    });
  });
};
const handleClickNode = (node) => {
  selectType.value = "";
  query.value = {
    userId,
    groupId: node.data.id,
  };
};
onMounted(() => {
  // getTreeSideData();
});
</script>

<style scoped lang="scss">
.home-content {
  display: flex;
  .side-menu {
    width: 400px;
    padding: 7px;
    border-left: 1px solid #eee;
    background-color: #f8f8f8;
    .head {
      display: flex;
      align-items: center;
      padding: 0 20px;
      margin-top: 15px;
      h1 {
        font-size: 18px;
        font-weight: 600;
        margin-left: 10px;
      }
    }
    .menu-body {
      margin: 15px 0;
      li {
        display: flex;
        font-size: 14px;
        padding: 8px 20px;
        border-radius: 5px;
        color: #262626;
        cursor: pointer;
        &:hover {
          background-color: #e8e8e8;
          opacity: 0.8;
        }
        span {
          margin-left: 10px;
        }
      }
      .active {
        background-color: #e8e8e8;
        opacity: 0.8;
      }
    }
    .tree-side {
      width: 100%;
      max-height: 500px;
      overflow: auto;
      h4 {
        font-size: 14px;
        padding: 5px 10px;
        margin-bottom: 5px;
        color: #989898;
      }
      .custom-tree-node {
        width: 100%;
        display: flex;
        justify-content: space-between;
        cursor: default;
        padding-right: 20px;
        .node-label:hover {
          text-decoration: underline;
          cursor: pointer;
        }
        .node-icon {
          display: flex;
          align-items: center;
          cursor: pointer;
          :deep(.el-icon):hover {
            color: #8901b4;
          }
        }
      }
      .add-tree-node {
        :deep(.el-input) {
          height: 22px;
        }
      }
    }
  }
}
:deep(.el-tree) {
  background: #f8f8f8;
}
</style>
